package com.bldby.baselibrary.core.network;

import android.app.AlertDialog;
import android.widget.LinearLayout;

import com.bldby.baselibrary.R;
import com.bldby.baselibrary.app.GlobalUtil;
import com.bldby.baselibrary.core.util.DeviceUtil;
import com.bldby.baselibrary.databinding.LayoutLoadingViewBinding;

import java.util.HashMap;

import pl.droidsonroids.gif.GifDrawable;

/**
 * Created by bch on 2020/5/15
 */
public class HttpLoadingUtil {
    /**
     * 用到的地方的数量
     */
    private static int usefulCount = 0;
    private static HashMap<String, BaseApiRequest> map = new HashMap<>();
    private static GifDrawable mAnimPull;
    private static AlertDialog alertDialog;

    //这个弹窗除了多个弹出框同事展示的问题,但是忽略一个问题就是activity切换时造成的问题
    synchronized private static void setLoadingViewShowWithContent(BaseApiRequest baseApiRequest, Boolean show, String content) {
        try {
            if (show) {
                try {
                    usefulCount++;
                    if (alertDialog == null) {

                        LayoutLoadingViewBinding inflate = LayoutLoadingViewBinding.inflate(GlobalUtil.getCurrentActivity().getLayoutInflater());
                        alertDialog = new AlertDialog.Builder(GlobalUtil.getCurrentActivity(), R.style.TransparentDialog)
                                .setView(inflate.getRoot())
                                .setCancelable(false)
                                .create();
                        alertDialog.getWindow().setDimAmount(0f);

                        alertDialog.show();
                        int i = DeviceUtil.dp2px(GlobalUtil.getCurrentActivity(), GlobalUtil.getCurrentActivity().getResources().getDimension(R.dimen.dp_50));
                        alertDialog.getWindow().setLayout(i, LinearLayout.LayoutParams.WRAP_CONTENT);
                        mAnimPull = (GifDrawable) inflate.img.getDrawable();
                        mAnimPull.start();
                    }
                } catch (Exception xc) {
                    xc.printStackTrace();
                }

            } else {
                usefulCount--;
                if (usefulCount <= 0 && alertDialog != null) {
                    alertDialog.dismiss();
                    alertDialog = null;
                    mAnimPull = null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setLoadingViewShow(BaseApiRequest baseApiRequest, Boolean show) {
        GlobalUtil.getCurrentActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                setLoadingViewShowWithContent(baseApiRequest, show, "加载中");
            }
        });
    }

}
